#include "DeadProxyGameThread.h"
#include "DeadProxyApp.h"

void* GameThread::Entry()
{
    int ip;
    short port;
    ////Recieve first packet
    int len;
    len = recv(serverSock, buffer, 65536, 0);

    ////Determine which client has connected
    int i;
    app->CManager->GetClientWithConnectStatus(6, &i);
    app->CManager->GetConnectingCharacterInfo(i, &ip, &port);
    ////convert ip into an address
    struct in_addr addr;
    addr.s_addr = ip;
    char ipstring[16];
    strcpy(ipstring, inet_ntoa(addr));
    ////Setup ClientSock
    int nret;
    LPHOSTENT hostEntry;
    hostEntry = gethostbyname(ipstring); // Specifying the server by its name;
    if (!hostEntry)
    {
        nret = WSAGetLastError();
        return NULL;
    }
    // Create the socket
    clientSock = socket(AF_INET, // Go over TCP/IP
                       SOCK_STREAM, // This is a stream-oriented socket
                       IPPROTO_TCP); // Use TCP rather than UDP
    if (clientSock == INVALID_SOCKET)
    {
        nret = WSAGetLastError();
        return NULL;
    }
    // Fill a SOCKADDR_IN struct with address information
    SOCKADDR_IN serverInfo;
    serverInfo.sin_family = AF_INET;
    serverInfo.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list);
    serverInfo.sin_port = htons(port); // Change to network-byte order and
    // Connect to the server;
    nret = connect(clientSock,
                  (LPSOCKADDR)&serverInfo,
                  sizeof(struct sockaddr));
    if (nret == SOCKET_ERROR)
    {
        return NULL;
    }

    ////send that original packet
    send(clientSock, buffer, len, 0);
    ////pass thread control to client
    app->CManager->PassGameControlTo((int)serverSock, (int)clientSock, i);
    //closesocket(serverSock);
    //closesocket(clientSock);
    
    return NULL;
}

GameThread::GameThread(SOCKET sSock)
{
    serverSock = sSock;
}

void GameThread::OnExit()
{
}
